#include "Screens\ScreenBase.h"

#include "SFML\OpenGL.hpp"
#include "SFML\Graphics\RenderWindow.hpp"

#include "Objects/Objects.h"
#include "Objects/Particle.h"

#include <iostream>

using namespace std;


ScreenBase::ScreenBase(GameState *gameState):
	m_gameState(gameState),
	m_nextId(1),
	m_objectLayers(MAX_LAYERS)
{
	for(int i = 0; i < MAX_PARTICLES; i++){
		m_particles[i] = new Particle(gameState);
	}

	m_currentParticle = 0;

	m_time = 0.0;
}


ScreenBase::~ScreenBase(){
	for(int i = 0; i < MAX_PARTICLES; i++){
		delete m_particles[i];
	}
}


void ScreenBase::init(){
	
	
	
}


void ScreenBase::update(double dt){
	list<GameObject*>::iterator it = m_objects.begin();

	while(it!=m_objects.end()){
		GameObject *object = (*it);
		if(object->isFirstUpdate()){
			object->firstUpdate();
			object->setFirstUpdate(false);
		}
		object->update(dt);
		
		if(!object->isAlive()){
			list<GameObject*>::iterator layerIt = m_objectLayers[object->getLayer()].begin();
			while(layerIt!=m_objectLayers[object->getLayer()].end()){
				if((*layerIt)==object){
					layerIt = m_objectLayers[object->getLayer()].erase(layerIt);
					break;
				}else{
					++layerIt;
				}
			}

			delete object;
			it = m_objects.erase(it);
		}else{
			++it;
		}
	}

	int count = 0;
	for(int i = 0; i < MAX_PARTICLES; i++){
		if(m_particles[i]->isAlive()){
			m_particles[i]->update(dt);
			count++;
		}
	}

	m_time += dt;
	
}


void ScreenBase::draw(){
	
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	
	glPushMatrix();
	{
		glTranslatef(-m_gameState->camera.posX, -m_gameState->camera.posY, 0);

		for(int i = MAX_LAYERS-1; i >= 0; i--){
			list<GameObject*>::iterator it;

			for(it = m_objectLayers[i].begin(); it!=m_objectLayers[i].end(); ++it){
				GameObject *object = (*it);
				object->draw();
				glColor3f(1.0f, 1.0f, 1.0f);
			}

			for(int j = 0; j < MAX_PARTICLES; j++){
				if(m_particles[i]->getLayer()==i && m_particles[j]->isAlive()){
					m_particles[j]->draw();
					glColor3f(1.0f, 1.0f, 1.0f);
				}
			}



			
		}
		
	}
	glPopMatrix();
}


void ScreenBase::addObject(GameObject* object, int layer){
	if(layer == -1){
		layer = object->getLayer();
	}

	object->setLayer(layer);
	object->setId(m_nextId);
	m_nextId++;
	m_objects.push_back(object);
	m_objectLayers[layer].push_back(object);

}

void ScreenBase::clean(){
	list<GameObject*>::iterator it = m_objects.begin();
	while(it!=m_objects.end()){
		delete (*it);
		++it;
	}
	m_objects.clear();

	for(unsigned int i = 0; i < m_objectLayers.size(); i++){
		m_objectLayers[i].clear();
	}

	
}


Particle* ScreenBase::createParticle(){
	Particle *chosen = m_particles[m_currentParticle];

	m_currentParticle ++; 

	m_currentParticle %= MAX_PARTICLES;

	chosen->init();

	return chosen;
}